package com.youaishujuhui.devops.web.controller.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youaishujuhui.devops.web.domain.game.Company;
import com.youaishujuhui.devops.web.domain.game.Department;
import com.youaishujuhui.devops.web.service.ConfigService;
import com.youaishujuhui.devops.web.service.game.CompanyService;
import com.youaishujuhui.devops.web.service.game.DepartmentService;

@Controller
@RequestMapping("/config")
public class ConfigController {
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private DepartmentService departmentService;

	@RequestMapping("/syncProduct")
    @ResponseBody
	public String syncProduct() {
		
		String jsonData = configService.loadProduct();
		 
	    JSONObject root = JSON.parseObject(jsonData);
	    
	    JSONArray companyList = root.getJSONArray("companyList");
	    
	    for(int i = 0; i < companyList.size(); i++){
	        JSONObject company = companyList.getJSONObject(i);  
	        int comId = company.getIntValue("id");
	        String simpleName = company.getString("simpleName");
	        String fullName = company.getString("fullName");
	        
	        Company c = new Company();
	        c.setComId(comId);
	        c.setFullName(fullName);
	        c.setSimpleName(simpleName);
	        
	        if (companyService.exists(comId)) {
	        	companyService._update(c);
	        } else {
	        	companyService._insert(c);
	        }
	        
	        JSONArray departmentList = company.getJSONArray("departmentList");
	        for(int j = 0; j < departmentList.size(); j++){
	        	JSONObject department = departmentList.getJSONObject(j);
	        	int deptId = department.getIntValue("id");
	        	comId = department.getIntValue("companyId");
	        	String deptName = department.getString("name");
	        	
	        	Department dept = new Department();
	        	dept.setDeptId(deptId);
	        	dept.setComId(comId);
	        	dept.setName(deptName);
	        	
	        	if (departmentService.exists(deptId)) {
	        		departmentService._update(dept);
		        } else {
		        	departmentService._insert(dept);
		        }
	        }
	    }
		
		return "ok";
	}
}
